<?php

class Form
{
  public $questions = array();
  private $school;
  
  
  public function addQuestion(Question $question)
  {
    $this->questions []= $question;
    return $this;
  }
  
  public function setSchool(School $school)
  {
    $this->school = $school;
  }
  
  public function render()
  {
    $this->school->log("form render");
    $html = '';
    $html .= '<form action="" method="post" name="formular">';
    foreach($this->questions as $question){
      $html .= $question->render();
    }
    $html .= '<input type="hidden" name="school_hash" value="' . $this->school->school_hash . '" />
<input type="submit" name="submit" value="Odoslať" />
</form>';
    return $html;
  }
  
  public function processPost($post)
  {
    $this->school->log("form post");
    Db::query("DELETE FROM schools_answers WHERE school_id = '".$this->school->school_id."';");
    $inserts = array();
    foreach($post as $key=>$value)
    {
      $answer = new Answer();
      try
      {
        $answer->loadByCode($key);
      }
      catch(Exception $e)
      {
        continue;
      }
      if($answer->answer_need_specify)
      {
        if(!empty($post[$key."_switcher"]))
        {
          $inserts []= '('.$this->school->school_id.','.$answer->answer_id.',"'.$value.'")';
        }
      }
      else
      {
        if($value == 'on')
        {
          $inserts []= '('.$this->school->school_id.','.$answer->answer_id.',NULL)';
        }
      }
    }
    $insert = "INSERT INTO schools_answers(school_id,answer_id,answer_specified) VALUES\n" . implode(",\n",$inserts) . ';';
    Db::query($insert);
    echo "Ďakujeme Vám že ste vyplnili náš dotazník.<br/>Toto okno môžete zatvoriť.<br/>";
  }
}
